﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Web.CrmContacto.Code;
using Web.Framework;
using CrmContacto.WebApp.Code.Sap;
using Web.CrmContacto.Code.Sap;
using Web.Framework.Translate;
using CrmContacto.WebApp.Code;
using System.Configuration;
using Web.CrmContacto.Code.Security;
using Web.Framework.Helpers;

namespace CrmContacto.WebApp.App
{
    public partial class ProductoSearch : BasePage
    {
        private string selectedItems = string.Empty;

        public int paisId
        {
            get
            {
                return Convert.ToInt32(ViewState["paisPorDefecto"]);
            }
            set
            {
                ViewState["paisPorDefecto"] = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!HasPermissionFor(CrmSecurity.PRODUCT_SEARCH))
                {
                    this.lnkBuscar.Visible =
                    this.lnkGuardar.Visible = false;
                    ShowMessage(LocalizationProvider.Instance["SinPermisosParaRealizarOperacion"] + CrmSecurity.PRODUCT_SEARCH, WebMessageType.Warning);
                }
                else
                {
                    this.lnkBuscar.Visible =
                    this.lnkGuardar.Visible = true;
                    this.lnkBuscar.Attributes.Add("aspnetid", this.lnkBuscar.ClientID);

                    if (!this.IsPostBack)
                    {
                        paisId = Convert.ToInt32(ConfigurationManager.AppSettings["paisPorDefecto"]);

                        string products = this.Request.QueryString["products"];
                        if (!String.IsNullOrEmpty(products))
                        {
                        }

                        //Buscar();
                    }

                    if (paisId == 55)
                    {
                        this.pColor.Attributes.Add("style", "display:none");
                    }
                }
            }
            catch (Exception ex)
            {
                //ExceptionManager.Instance.HandleException(ex); // TODO: sin master no funciona
                ShowMessage(ExceptionManager.Instance.GetExceptionMessage(ex) + ExceptionManager.Instance.GetExceptionStackTrace(ex), WebMessageType.Error);
            }
        }

        public void ShowMessage(string message, WebMessageType type)
        {
            ShowMessage(LocalizationProvider.Instance["Bo.Messages.Mensaje"], message, type);
        }

        public void ShowMessage(string title, string message, WebMessageType type)
        {
            this.pnlMessages.CssClass = "pnlMessagesClass displayBlock";
            this.txtErrorTitle.Text = title;
            this.txtMessages.Text = message;
            if (type != WebMessageType.Error)
            {
                pnlError.CssClass = "errorPanelMessage";
            }
            else
            {
                pnlError.CssClass = "errorPanelError";
            }
        }

        private void Buscar()
        {            
            SapCheckMantRDescParam param = new SapCheckMantRDescParam();
            param.Producto = this.txtCodigoProducto.Text;
            param.Color = this.txtCodigoColorProducto.Text;
            param.Descripcion = this.txtDescripcion.Text;

            var empConfig = BasePage.GetCompanyConfigurationKeyValue(this, BaseWebPage.CompanyId).Where(c => c.Key == "CodigoSAP").Single();
            param.Empresa = empConfig.Value;

            if (String.IsNullOrEmpty(param.Producto) && String.IsNullOrEmpty(param.Color) && String.IsNullOrEmpty(param.Descripcion))
            {
                ShowMessage(LocalizationProvider.Instance["Bo.ProductoSearch.ValidacionCodigo"], WebMessageType.Error);
            }
            else
            {
                List<SapCodigoProductoCompleto> returnList = new List<SapCodigoProductoCompleto>();

                PaisFront paisFront = PaisFront.GetPais(paisId, BaseWebPage.CompanyId);

                returnList.AddRange(paisFront.GetProductos(param));

                this.Grid.DataSource = returnList;
                this.Grid.DataBind();

                pnlResults.Visible = true;
                pnlResultsGroup.Visible = true;
            }
        }        

        protected void Grid_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {                   
                }
            }
            catch (Exception ex)
            {
                ShowMessage(ExceptionManager.Instance.GetExceptionMessage(ex) + ExceptionManager.Instance.GetExceptionStackTrace(ex), WebMessageType.Error);
            }
        }

        protected void Grid_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {               
            }
            catch (Exception ex)
            {
                ShowMessage(ExceptionManager.Instance.GetExceptionMessage(ex) + ExceptionManager.Instance.GetExceptionStackTrace(ex), WebMessageType.Error);
            }
        }

        protected void Grid_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                this.Grid.PageIndex = e.NewPageIndex;

                Buscar();
            }
            catch (Exception ex)
            {
                ShowMessage(ExceptionManager.Instance.GetExceptionMessage(ex) + ExceptionManager.Instance.GetExceptionStackTrace(ex), WebMessageType.Error);
            }
        }

        protected void lnkBuscar_Click(object sender, EventArgs e)
        {
            try
            {                
                Buscar();
            }
            catch (Exception ex)
            {
                ShowMessage(ExceptionManager.Instance.GetExceptionMessage(ex) + ExceptionManager.Instance.GetExceptionStackTrace(ex), WebMessageType.Error);
            }
        }

        protected void lnkExportarAExcel_Click(object sender, EventArgs e)
        {
            try
            {
                bool previousAllowPaging = this.Grid.AllowPaging;
                this.Grid.AllowPaging = false;

                Buscar();

                GridViewExportExcelUtil.Export("Productos.xls", this.Grid, 0, 1);

                this.Grid.AllowPaging = previousAllowPaging;
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }
    }
}